package cn.wolfcode.mq;

import cn.wolfcode.domain.OperateIntergralVo;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.mapper.OrderInfoMapper;
import cn.wolfcode.service.IOrderInfoService;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

/**
 * @author hkj
 * @email 1349091387@qq.com
 * @date 2022/1/6
 * 源码允许修改，并且本人十分乐意有 大佬 来对代码进行 随 意 调 教
 **/
@Component
@RocketMQTransactionListener(txProducerGroup = "tx_group")
public class OrderTXMsgListener implements RocketMQLocalTransactionListener {

    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    /**
     * 执行本地事务
     * @param message
     * @param obj 事务消息传递过来的第四个参数 orderNo
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object obj) {
        RocketMQLocalTransactionState state = null;
        try {
            String orderNo = (String) obj;
            state = RocketMQLocalTransactionState.COMMIT;
            orderInfoService.changeOrderStatus(orderNo);

        }catch (Exception e){
            e.printStackTrace();
            state = RocketMQLocalTransactionState.ROLLBACK;
        }
        return state;
    }

    /**
     * 回查本地事务方法
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String stringObj = new String((byte[]) message.getPayload());
        OperateIntergralVo vo = JSON.parseObject(stringObj, OperateIntergralVo.class);
        OrderInfo orderInfo = orderInfoMapper.select(vo.getPk());
        if(OrderInfo.STATUS_REFUND.equals(orderInfo.getStatus())){
            return RocketMQLocalTransactionState.COMMIT;
        }else{
            return RocketMQLocalTransactionState.ROLLBACK;
        }

    }
}
